import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import axios from 'axios';
import { message } from 'antd';

const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || 'http://localhost:5197';

// 查询键工厂
export const weatherQueryKeys = {
  all: ['weather'] as const,
  lists: () => [...weatherQueryKeys.all, 'list'] as const,
  list: (filters: Record<string, any>) => [...weatherQueryKeys.lists(), filters] as const,
  details: () => [...weatherQueryKeys.all, 'detail'] as const,
  detail: (id: string) => [...weatherQueryKeys.details(), id] as const,
  stats: () => [...weatherQueryKeys.all, 'stats'] as const,
  statistics: (cityId: string, filters?: Record<string, any>) => 
    [...weatherQueryKeys.all, 'statistics', cityId, filters] as const,
};

export const cityQueryKeys = {
  all: ['cities'] as const,
  lists: () => [...cityQueryKeys.all, 'list'] as const,
  list: (filters?: Record<string, any>) => [...cityQueryKeys.lists(), filters] as const,
};

// 天气数据查询
export function useWeatherData(filters?: {
  cityId?: string;
  startDate?: string;
  endDate?: string;
  page?: number;
  pageSize?: number;
}) {
  return useQuery({
    queryKey: weatherQueryKeys.list(filters || {}),
    queryFn: async () => {
      const params: any = {
        page: filters?.page || 1,
        pageSize: filters?.pageSize || 100,
        ...filters
      };
      
      const response = await axios.get(`${API_BASE_URL}/api/weather`, { params });
      const responseData = response.data;
      
      if (responseData && Array.isArray(responseData.data)) {
        return responseData.data;
      } else if (Array.isArray(responseData)) {
        return responseData;
      } else {
        return [];
      }
    },
    enabled: true,
  });
}

// 天气统计数据查询
export function useWeatherStats() {
  return useQuery({
    queryKey: weatherQueryKeys.stats(),
    queryFn: async () => {
      const response = await axios.get(`${API_BASE_URL}/api/statistics/overview`);
      return response.data;
    },
    refetchInterval: 30000, // 每30秒自动刷新
  });
}

// 城市列表查询
export function useCities() {
  return useQuery({
    queryKey: cityQueryKeys.list(),
    queryFn: async () => {
      const response = await axios.get(`${API_BASE_URL}/api/weather/cities`);
      return response.data;
    },
  });
}

// 统计数据查询
export function useStatistics(cityId?: string, filters?: {
  startDate?: string;
  endDate?: string;
}) {
  return useQuery({
    queryKey: weatherQueryKeys.statistics(cityId || '', filters),
    queryFn: async () => {
      if (!cityId) return [];
      
      const url = `${API_BASE_URL}/api/weather/statistics/range/${cityId}`;
      const params: any = {};
      
      if (filters?.startDate) params.startDate = filters.startDate;
      if (filters?.endDate) params.endDate = filters.endDate;
      
      const response = await axios.get(url, { params });
      return response.data || [];
    },
    enabled: !!cityId,
  });
}

// 数据采集突变
export function useSimulateDataCollection() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: async (params: { baseTemperature?: number; count?: number } = {}) => {
      const response = await axios.post(`${API_BASE_URL}/api/weather/simulate`, {
        baseTemperature: params.baseTemperature || 20,
        count: params.count || 3
      });
      return response.data;
    },
    onSuccess: (data) => {
      message.success(`数据生成成功！为 ${data.cityCount} 个城市生成了 ${data.totalDataGenerated} 条天气数据`);
      
      // 使相关查询失效，触发重新获取
      queryClient.invalidateQueries({ queryKey: weatherQueryKeys.all });
    },
    onError: () => {
      message.error('启动数据采集失败');
    },
  });
}

// 城市管理突变
export function useCityManagement() {
  const queryClient = useQueryClient();
  
  const createCity = useMutation({
    mutationFn: async (cityData: any) => {
      const response = await axios.post(`${API_BASE_URL}/api/weather/cities`, cityData);
      return response.data;
    },
    onSuccess: () => {
      message.success('城市添加成功');
      queryClient.invalidateQueries({ queryKey: cityQueryKeys.all });
    },
    onError: () => {
      message.error('城市添加失败');
    },
  });

  const updateCity = useMutation({
    mutationFn: async (params: { id: string; cityData: any }) => {
      const response = await axios.put(`${API_BASE_URL}/api/weather/cities/${params.id}`, params.cityData);
      return response.data;
    },
    onSuccess: () => {
      message.success('城市更新成功');
      queryClient.invalidateQueries({ queryKey: cityQueryKeys.all });
    },
    onError: () => {
      message.error('城市更新失败');
    },
  });

  const deleteCity = useMutation({
    mutationFn: async (cityId: string) => {
      await axios.delete(`${API_BASE_URL}/api/weather/cities/${cityId}`);
      return cityId;
    },
    onSuccess: () => {
      message.success('城市删除成功');
      queryClient.invalidateQueries({ queryKey: cityQueryKeys.all });
    },
    onError: () => {
      message.error('城市删除失败');
    },
  });

  const toggleStatus = useMutation({
    mutationFn: async (params: { cityId: string; isActive: boolean }) => {
      await axios.patch(`${API_BASE_URL}/api/weather/cities/${params.cityId}/status`, {
        isActive: params.isActive
      });
      return params;
    },
    onSuccess: (data) => {
      message.success(`城市已${data.isActive ? '激活' : '停用'}`);
      queryClient.invalidateQueries({ queryKey: cityQueryKeys.all });
    },
    onError: () => {
      message.error('状态更新失败');
    },
  });

  return {
    createCity,
    updateCity,
    deleteCity,
    toggleStatus,
  };
}